package com.cfswt.tasksystem.controller;

import com.cfswt.tasksystem.mapper.*;
import com.cfswt.tasksystem.pojo.dto.*;
import com.cfswt.tasksystem.pojo.entity.*;
import com.cfswt.tasksystem.pojo.vo.*;
import com.cfswt.tasksystem.response.JsonResult;
import com.cfswt.tasksystem.security.CustomUserDetails;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.impl.identity.Authentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Api(tags = "22.KPI模块")
@RestController
@RequestMapping("/kpi")
public class KPIController {
    @Autowired
    private KPIMapper kpiMapper;
    @Autowired
    private KPIAttachmentMapper kpiAttachmentMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskRuntime taskRuntime;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private TaskAttachmentMapper taskAttachmentMapper;
    @Autowired
    private TaskSummaryMapper taskSummaryMapper;
    @Autowired
    private TaskDelayMapper taskDelayMapper;
    @Autowired
    private TaskMilestoneMapper taskMilestoneMapper;
    @Autowired
    private TaskCommentMapper taskCommentMapper;
    @Autowired
    private TaskCompleteSummaryMapper taskCompleteSummaryMapper;
    @Autowired
    private TaskPlanSummaryMapper taskPlanSummaryMapper;
    @Autowired
    private TaskCoordinateSummaryMapper taskCoordinateSummaryMapper;
    @Autowired
    private ReminderMapper reminderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ReminderUserMapper reminderUserMapper;
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @ApiOperation(value = "发布KPI")
    @Transactional
    @PostMapping("/release/")
    public JsonResult releaseKPI(@RequestBody KPIPartyReleaseDTO kpiPartyReleaseDTO, @AuthenticationPrincipal CustomUserDetails userDetails) {
        kpiPartyReleaseDTO.setCreateTime(new Date());
        kpiMapper.insertKPI(kpiPartyReleaseDTO);
        IndicatorTaskBookAttachment indicatorTaskBookAttachment = kpiPartyReleaseDTO.getIndicatorTaskBookAttachment();
        indicatorTaskBookAttachment.setKpiId(kpiPartyReleaseDTO.getId());
        indicatorTaskBookAttachment.setCreateBy(userDetails.getNickName());
        indicatorTaskBookAttachment.setCreateTime(new Date());
        kpiAttachmentMapper.insertKPIIndicatorTaskBook(indicatorTaskBookAttachment);
        List<PrimaryIndicatorDTO> primaryIndicatorDTOS = kpiPartyReleaseDTO.getPrimaryIndicators();
        for (PrimaryIndicatorDTO primary : primaryIndicatorDTOS) {
            primary.setKpiId(kpiPartyReleaseDTO.getId());
            kpiMapper.insertPrimaryIndicator(primary); // 插入主指标，数据库生成id
            Integer primaryId = primary.getId(); // 假设插入后id会回填到对象
            for (IndicatorPointDTO point : primary.getPoints()) {
                point.setPrimaryId(primaryId); // 设置外键
                kpiMapper.insertIndicatorPoint(point);
                Integer pointId = point.getId();
                for (IndicatorDetailDTO detail : point.getDetails()) {
                    detail.setPointId(pointId); // 设置外键
                    kpiMapper.insertIndicatorDetail(detail);
                }
            }
        }
        List<PrimaryIndicatorPlanDTO> primaryIndicatorPlanDTOS = kpiPartyReleaseDTO.getPrimaryIndicatorPlans();
        for (PrimaryIndicatorPlanDTO primaryPlan : primaryIndicatorPlanDTOS) {
            primaryPlan.setKpiId(kpiPartyReleaseDTO.getId());
            kpiMapper.insertPrimaryIndicatorPlan(primaryPlan); // 插入主指标，数据库生成id
            Integer primaryId = primaryPlan.getId(); // 假设插入后id会回填到对象
            for (IndicatorPointPlanDTO pointPlan : primaryPlan.getPoints()) {
                pointPlan.setPrimaryId(primaryId); // 设置外键
                kpiMapper.insertIndicatorPointPlan(pointPlan);
                Integer pointId = pointPlan.getId();
                for (IndicatorDetailPlanDTO detailPlan : pointPlan.getDetails()) {
                    detailPlan.setPointId(pointId); // 设置外键
                    kpiMapper.insertIndicatorDetailPlan(detailPlan);
                }
            }
        }
        return JsonResult.ok();
    }

    @ApiOperation(value = "KPI中新增/更新自定义指标")
    @PostMapping("/release/custom_task")
    @Transactional(rollbackFor = Exception.class)
    public JsonResult releaseCustomTask(@RequestBody KPIPartyReleaseDTO dto) {
        Integer kpiId = dto.getId();
        List<CustomPrimaryIndicatorPlanDTO> primaries = dto.getCustomPrimaryIndicatorPlanDTOS();
        if (primaries == null) return JsonResult.ok();

        for (CustomPrimaryIndicatorPlanDTO p : primaries) {
            Integer primaryId = p.getId();
            p.setKpiId(kpiId);

            if (primaryId == null) {
                // 插入主指标
                kpiMapper.insertCustomPrimaryIndicatorPlan(p); // 需要 useGeneratedKeys 回填 id
                primaryId = p.getId();
            } else {
                // 更新主指标（只更新名称等可变字段）
                kpiMapper.updateCustomPrimaryIndicatorPlanById(p);
            }

            if (p.getPoints() == null) continue;
            for (CustomIndicatorPointPlanDTO pt : p.getPoints()) {
                Integer pointId = pt.getId();
                pt.setPrimaryId(primaryId);

                if (pointId == null) {
                    kpiMapper.insertCustomIndicatorPointPlan(pt); // 回填 id
                    pointId = pt.getId();
                } else {
                    kpiMapper.updateCustomIndicatorPointPlanById(pt);
                }

                if (pt.getDetails() == null) continue;
                for (CustomIndicatorDetailPlanDTO d : pt.getDetails()) {
                    Integer detailId = d.getId();
                    d.setPointId(pointId);

                    if (detailId == null) {
                        kpiMapper.insertCustomIndicatorDetailPlan(d);
                    } else {
                        kpiMapper.updateCustomIndicatorDetailPlanById(d);
                    }
                }
            }
        }

        return JsonResult.ok();
    }

    @ApiOperation(value = "党建KPI年度列表页")
    @GetMapping("/list/")
    public JsonResult selectKPIListVO() {
        List<KPIPartyListVO> kpiPartyListVOS = kpiMapper.selectKPIListVO();
        for (KPIPartyListVO kpiPartyListVO : kpiPartyListVOS) {
            IndicatorTaskBookAttachment indicatorTaskBookAttachment = kpiAttachmentMapper.selectKPIIndicatorTaskBookByKpiId(kpiPartyListVO.getId());
            kpiPartyListVO.setIndicatorTaskBookAttachment(indicatorTaskBookAttachment);
        }
        System.out.println(kpiPartyListVOS);
        return JsonResult.ok(kpiPartyListVOS);
    }

    @ApiOperation(value = "党建年度KPI完整页面")
    @GetMapping("/detail/{id}")
    public JsonResult selectKPIDetail(@PathVariable Integer id) {
        KPIPartyVO kpiPartyVO = kpiMapper.selectKPIPartyVOById(id);
        List<PrimaryIndicatorVO> primaryIndicatorVOS = kpiMapper.selectPrimaryIndicatorByKPIId(id);
        for (PrimaryIndicatorVO primaryIndicatorVO : primaryIndicatorVOS) {
            List<IndicatorPointVO> indicatorPointVOS = kpiMapper.selectIndicatorPointsByPrimaryId(primaryIndicatorVO.getId());
            for (IndicatorPointVO indicatorPointVO : indicatorPointVOS) {
                List<IndicatorDetailVO> indicatorDetailVOS = kpiMapper.selectIndicatorDetailsByPointId(indicatorPointVO.getId());
                indicatorPointVO.setIndicatorDetailVOS(indicatorDetailVOS);
            }
            primaryIndicatorVO.setIndicatorPointVOS(indicatorPointVOS);
        }
        List<PrimaryIndicatorPlanVO> primaryIndicatorPlanVOS = kpiMapper.selectPrimaryIndicatorPlanByKPIId(id);
        for (PrimaryIndicatorPlanVO primaryIndicatorPlanVO : primaryIndicatorPlanVOS) {
            List<IndicatorPointPlanVO> indicatorPointPlanVOS = kpiMapper.selectIndicatorPointsPlanByPrimaryId(primaryIndicatorPlanVO.getId());
            for (IndicatorPointPlanVO indicatorPointPlanVO : indicatorPointPlanVOS) {
                List<IndicatorDetailPlanVO> indicatorDetailPlanVOS = kpiMapper.selectIndicatorDetailsPlanByPointId(indicatorPointPlanVO.getId());
                indicatorPointPlanVO.setIndicatorDetailPlanVOS(indicatorDetailPlanVOS);
            }
            primaryIndicatorPlanVO.setIndicatorPointPlanVOS(indicatorPointPlanVOS);
        }
        List<CustomPrimaryIndicatorPlanVO> customPrimaryIndicatorPlanVOS = kpiMapper.selectCustomPrimaryIndicatorPlanByKPIId(id);
        for (CustomPrimaryIndicatorPlanVO customPrimaryIndicatorPlanVO : customPrimaryIndicatorPlanVOS) {
            List<CustomIndicatorPointPlanVO> customIndicatorPointPlanVOS = kpiMapper.selectCustomIndicatorPointsPlanByPrimaryId(customPrimaryIndicatorPlanVO.getId());
            for (CustomIndicatorPointPlanVO customIndicatorPointPlanVO : customIndicatorPointPlanVOS) {
                List<CustomIndicatorDetailPlanVO> customIndicatorDetailPlanVOS = kpiMapper.selectCustomIndicatorDetailsPlanByPointId(customIndicatorPointPlanVO.getId());
                customIndicatorPointPlanVO.setCustomIndicatorDetailPlanVOS(customIndicatorDetailPlanVOS);
            }
            customPrimaryIndicatorPlanVO.setCustomIndicatorPointPlanVOS(customIndicatorPointPlanVOS);
        }
        kpiPartyVO.setPrimaryIndicatorVOS(primaryIndicatorVOS);
        kpiPartyVO.setPrimaryIndicatorPlanVOS(primaryIndicatorPlanVOS);
        kpiPartyVO.setCustomPrimaryIndicatorPlanVOS(customPrimaryIndicatorPlanVOS);
        System.out.println(kpiPartyVO);
        return JsonResult.ok(kpiPartyVO);
    }

    @ApiOperation(value = "党建年度KPI指标修改")
    @PostMapping("/indicatorKPI/update")
    public JsonResult updateIndicatorKPIByIndicatorId(@RequestBody KPIItemDTO kpiItemDTO) {
        Integer indicatorDetailId = kpiItemDTO.getIndicatorDetailId();
        return JsonResult.ok();
    }

    @ApiOperation(value = "党建年度KPI计划修改")
    @PostMapping("/indicatorPlan/update")
    public JsonResult updateIndicatorPlanByIndicatorId(@RequestBody KPIItemDTO kpiItemDTO) {
        return JsonResult.ok();
    }

    @Transactional
    @ApiOperation(value = "党建KPI发布指标任务")
    @PostMapping("/indicator/task")
    public JsonResult releaseIndicatorTask(@RequestBody IndicatorDetailTask indicatorDetailTask, @AuthenticationPrincipal CustomUserDetails userDetails) {
        indicatorDetailTask.setCreateBy(userDetails.getNickName());
        Date endTime = indicatorDetailTask.getEndTime();
        System.out.println(indicatorDetailTask);
        kpiMapper.insertIndicatorTask(indicatorDetailTask);
        String type = indicatorDetailTask.getType();
        switch (type) {
            case "kpi":
                kpiMapper.updateIndicatorDetailByIds(indicatorDetailTask);
                break;
            case "plan":
                kpiMapper.updateIndicatorDetailPlanByIds(indicatorDetailTask);
                break;
            case "custom":
                kpiMapper.updateCustomIndicatorDetailPlanByIds(indicatorDetailTask);
                break;
        }
        Integer id = indicatorDetailTask.getId();
        ReminderVO reminderVO = new ReminderVO();
        reminderVO.setRemindTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(indicatorDetailTask.getCreateTime()));
        reminderVO.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
        reminderVO.setRelatedId(id.toString());
        reminderVO.setType("KPI指标任务通知");
        reminderVO.setSender(userDetails.getNickName());
        reminderVO.setTitle(indicatorDetailTask.getTitle());
        reminderVO.setSummary(indicatorDetailTask.getCreateBy());
        reminderVO.setStatus(ReminderVO.Status.fromString("未读"));
        reminderMapper.insertReminder(reminderVO);
        Integer reminderVOId = reminderVO.getId();
        Integer userId = userMapper.selectIdByNickName(indicatorDetailTask.getPersonInCharge());
        ReminderUser reminderUser = new ReminderUser();
        reminderUser.setUserId(userId);
        reminderUser.setReminderId(reminderVOId);
        reminderUser.setCreateTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
        reminderUserMapper.insertReminderUser(reminderUser);
        String userName = userMapper.selectUserNameByNickName(indicatorDetailTask.getPersonInCharge());
        System.out.println("Sending message to user: " + userName + " at /queue/meeting-notification");
        simpMessagingTemplate.convertAndSendToUser(userName, "/queue/meeting-notification", reminderVO);
        System.out.println(reminderVO);
        return JsonResult.ok(id);
    }

    @ApiOperation(value = "党建KPI更新指标任务")
    @PostMapping("/indicator/update_task")
    public JsonResult updateIndicatorTask(@RequestBody IndicatorDetailTask indicatorDetailTask, @AuthenticationPrincipal CustomUserDetails userDetails) {
        System.out.println("更新后的指标任务数据：" + indicatorDetailTask);
        kpiMapper.updateIndicatorTask(indicatorDetailTask);
        Integer id = indicatorDetailTask.getId();
        ReminderVO reminderVO = new ReminderVO();
        reminderVO.setRemindTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(indicatorDetailTask.getCreateTime()));
        reminderVO.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
        reminderVO.setRelatedId(id.toString());
        reminderVO.setType("KPI指标任务通知");
        reminderVO.setSender(userDetails.getNickName());
        reminderVO.setTitle(indicatorDetailTask.getTitle());
        reminderVO.setSummary(indicatorDetailTask.getCreateBy());
        reminderVO.setStatus(ReminderVO.Status.fromString("未读"));
        reminderMapper.insertReminder(reminderVO);
        Integer reminderVOId = reminderVO.getId();
        Integer userId = userMapper.selectIdByNickName(indicatorDetailTask.getPersonInCharge());
        ReminderUser reminderUser = new ReminderUser();
        reminderUser.setUserId(userId);
        reminderUser.setReminderId(reminderVOId);
        reminderUser.setCreateTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
        reminderUserMapper.insertReminderUser(reminderUser);
        String userName = userMapper.selectUserNameByNickName(indicatorDetailTask.getPersonInCharge());
        System.out.println("Sending message to user: " + userName + " at /queue/meeting-notification");
        simpMessagingTemplate.convertAndSendToUser(userName, "/queue/meeting-notification", reminderVO);
        System.out.println(reminderVO);
        return JsonResult.ok();
    }

    @ApiOperation(value = "党建KPI显示指标任务")
    @GetMapping("/indicator/task/{kpiId}/{indicatorDetailId}")
    public JsonResult getIndicatorTaskByIds(@PathVariable Integer kpiId, @PathVariable Integer indicatorDetailId) {
        IndicatorDetailTask indicatorDetailTask = kpiMapper.selectIndicatorTaskByIds(kpiId, indicatorDetailId);
        System.out.println("指标任务数据为" + indicatorDetailTask);
        return JsonResult.ok(indicatorDetailTask);
    }

    @ApiOperation(value = "新增或更新方案(审批前)")
    @Transactional
    @PostMapping("/detail/scheme/addOrUpdate")
    public JsonResult addOrUpdatePartyScheme(@RequestBody SubmitSchemeDTO submitSchemeDTO,
                                             @AuthenticationPrincipal CustomUserDetails userDetails) {
        List<IndicatorDetailScheme> incomingSchemes = submitSchemeDTO.getIndicatorDetailSchemes();
        List<Integer> attachmentsToDelete = submitSchemeDTO.getAttachmentsToDelete();
        // 判断方案数据是否为空
        if (incomingSchemes == null || incomingSchemes.isEmpty()) {
            return JsonResult.ok();
        }
        Integer indicatorDetailId = incomingSchemes.get(0).getIndicatorDetailId();
        List<IndicatorDetailScheme> dbSchemes = kpiMapper.selectDetailSchemeByDetailId(indicatorDetailId);
        boolean isFirstSubmit = (dbSchemes == null || dbSchemes.isEmpty());

        // 如果是首次提交，启动流程并获取流程实例ID；非首次提交从数据库继承流程实例ID
        String processInstanceId = null;
        if (isFirstSubmit) {
            String processDefinitionKey = "Process_9";
            String businessKey = "党建方案审批-" + userDetails.getNickName();
            String username = userDetails.getUsername();
            Map<String, Object> variables = new HashMap<>();
            variables.put("creator", username);
            Authentication.setAuthenticatedUserId(username);
            processInstanceId = runtimeService
                    .startProcessInstanceByKey(processDefinitionKey, businessKey, variables)
                    .getProcessInstanceId();
        } else {
            // 非首次提交：从已有记录中继承流程实例ID（通常相同，取第一条非空即可）
            processInstanceId = dbSchemes.stream()
                    .filter(s -> s.getProcessInstanceId() != null)
                    .map(s -> s.getProcessInstanceId())
                    .findFirst()
                    .orElse(null);
        }
        Date now = new Date();
        for (IndicatorDetailScheme scheme : incomingSchemes) {
            if (scheme.getId() == null) {
                // 新增行：继承流程实例ID（首次为新启动的，非首次为库中已有的），状态为"未审批"，版本为0
                scheme.setProcessInstanceId(processInstanceId);
                scheme.setStatus("未审批");
                scheme.setVersion(0);
                scheme.setCreateTime(now);
                kpiMapper.insertDetailScheme(scheme);
            } else {
                // 更新行：如果内容有变化则更新版本号，保持原流程实例ID和状态
                IndicatorDetailScheme existingScheme = dbSchemes.stream()
                        .filter(s -> s.getId().equals(scheme.getId()))
                        .findFirst().orElse(null);

                if (existingScheme != null) {
                    boolean hasChanged = isSchemeChanged(existingScheme, scheme);
                    int oldVersion = existingScheme.getVersion() == null ? 0 : existingScheme.getVersion();
                    int newVersion = hasChanged ? oldVersion + 1 : oldVersion;

                    scheme.setProcessInstanceId(existingScheme.getProcessInstanceId()); // 保持原流程实例ID
                    scheme.setStatus(existingScheme.getStatus()); // 保持原状态
                    scheme.setVersion(newVersion); // 如果有变化，版本号+1
                    kpiMapper.updateDetailScheme(scheme);
                }
            }
            // 处理附件：如果附件是新增的，则插入
            if (scheme.getKpiSchemeAttachments() != null) {
                for (KPISchemeAttachment attachment : scheme.getKpiSchemeAttachments()) {
                    if (attachment.getId() == null) {
                        attachment.setIndicatorDetailSchemeId(scheme.getId());
                        attachment.setCreateTime(now);
                        attachment.setCreateBy(userDetails.getNickName());
                        kpiAttachmentMapper.insertAttachment(attachment);
                    }
                }
            }
        }
        // 删除附件
        if (attachmentsToDelete != null && !attachmentsToDelete.isEmpty()) {
            for (Integer id : attachmentsToDelete) {
                kpiAttachmentMapper.deleteAttachmentById(id);
            }
        }

        return JsonResult.ok();
    }

    // 判断方案是否有变更
    private boolean isSchemeChanged(IndicatorDetailScheme oldOne, IndicatorDetailScheme newOne) {
        if (!Objects.equals(oldOne.getSchemeContent(), newOne.getSchemeContent())) {
            return true;
        }
        return false;
    }

    @ApiOperation(value = "更新流程中的方案(审批退回后修改)")
    @Transactional
    @PostMapping("/detail/scheme/update_process_scheme")
    public JsonResult updateProcessScheme(@RequestBody SubmitSchemeDTO submitSchemeDTO,
                                          @AuthenticationPrincipal CustomUserDetails userDetails) {
        List<IndicatorDetailScheme> incomingSchemes = submitSchemeDTO.getIndicatorDetailSchemes();
        List<Integer> attachmentsToDelete = submitSchemeDTO.getAttachmentsToDelete();
        Integer indicatorDetailId = incomingSchemes.get(0).getIndicatorDetailId();
        List<IndicatorDetailScheme> dbSchemes = kpiMapper.selectDetailSchemeByDetailId(indicatorDetailId);
        if (incomingSchemes == null || incomingSchemes.isEmpty()) {
            return JsonResult.ok();
        }
        boolean isFirstSubmit = (dbSchemes == null || dbSchemes.isEmpty());
        // 获取第一个方案的流程实例ID（所有方案应该属于同一个流程实例）
        String processInstanceId = null;
        for (IndicatorDetailScheme scheme : incomingSchemes) {
            if (scheme.getProcessInstanceId() != null) {
                processInstanceId = scheme.getProcessInstanceId();
                break;
            }
        }
        Page<Task> tasks = taskRuntime.tasks(
                Pageable.of(0, 50), // 取足够多，防止有多个并行任务
                TaskPayloadBuilder
                        .tasks()
                        .withProcessInstanceId(processInstanceId)
                        .build()
        );
        Task currentTask = null;
        for (Task task : tasks.getContent()) {
            if ("方案修改".equals(task.getName()) && userDetails.getUsername().equals(task.getAssignee())) {
                currentTask = task;
                break;
            }
        }
        Date now = new Date();
        for (IndicatorDetailScheme scheme : incomingSchemes) {
            if (scheme.getId() == null) {
                // 新增行：继承流程实例ID（首次为新启动的，非首次为库中已有的），状态为"未审批"，版本为0
                scheme.setProcessInstanceId(processInstanceId);
                scheme.setStatus("未审批");
                scheme.setVersion(0);
                scheme.setCreateTime(now);
                kpiMapper.insertDetailScheme(scheme);
            } else {
                // 更新行：如果内容有变化则更新版本号，保持原流程实例ID和状态
                IndicatorDetailScheme existingScheme = dbSchemes.stream()
                        .filter(s -> s.getId().equals(scheme.getId()))
                        .findFirst().orElse(null);

                if (existingScheme != null) {
                    boolean hasChanged = isSchemeChanged(existingScheme, scheme);
                    int oldVersion = existingScheme.getVersion() == null ? 0 : existingScheme.getVersion();
                    int newVersion = hasChanged ? oldVersion + 1 : oldVersion;

                    scheme.setProcessInstanceId(existingScheme.getProcessInstanceId()); // 保持原流程实例ID
                    scheme.setStatus(existingScheme.getStatus()); // 保持原状态
                    scheme.setVersion(newVersion); // 如果有变化，版本号+1
                    kpiMapper.updateDetailScheme(scheme);
                }
            }
            // 处理附件：如果附件是新增的，则插入
            if (scheme.getKpiSchemeAttachments() != null) {
                for (KPISchemeAttachment attachment : scheme.getKpiSchemeAttachments()) {
                    if (attachment.getId() == null) {
                        attachment.setIndicatorDetailSchemeId(scheme.getId());
                        attachment.setCreateTime(now);
                        attachment.setCreateBy(userDetails.getNickName());
                        kpiAttachmentMapper.insertAttachment(attachment);
                    }
                }
            }
        }
        if (attachmentsToDelete != null && !attachmentsToDelete.isEmpty()) {
            for (Integer id : attachmentsToDelete) {
                kpiAttachmentMapper.deleteAttachmentById(id);
            }
        }
        taskRuntime.complete(
                TaskPayloadBuilder.complete()
                        .withTaskId(currentTask.getId())
                        .build()
        );
        return JsonResult.ok("方案更新成功，已提交复审");
    }


    @ApiOperation(value = "指标任务方案删除")
    @DeleteMapping("/detail/scheme/{id}")
    public JsonResult deleteDetailSchemeById(@PathVariable Integer id) {
        kpiMapper.deleteDetailSchemeByDetailId(id);
        return JsonResult.ok();
    }

    @ApiOperation(value = "指标任务方案显示")
    @GetMapping("/detail/scheme/{id}")
    public JsonResult getSchemeBySchemeIdAndMaxVersion(@PathVariable Integer id) {
        System.out.println("kpi事项id:" + id);
        List<IndicatorDetailScheme> indicatorDetailSchemes = kpiMapper.selectDetailSchemeByDetailId(id);
        for (IndicatorDetailScheme indicatorDetailScheme : indicatorDetailSchemes) {
            List<KPISchemeAttachment> kpiSchemeAttachments = kpiAttachmentMapper.selectAttachmentBySchemeId(indicatorDetailScheme.getId());
            indicatorDetailScheme.setKpiSchemeAttachments(kpiSchemeAttachments);
        }
        System.out.println(indicatorDetailSchemes);
        return JsonResult.ok(indicatorDetailSchemes);
    }

    @ApiOperation(value = "指标任务的审批方案显示")
    @GetMapping("/scheme/{taskId}")
    public JsonResult getSchemeByTaskId(@PathVariable String taskId) {
        System.out.println("任务id:" + taskId);
        String processInstanceId = taskRuntime.task(taskId).getProcessInstanceId();
        List<IndicatorDetailSchemeApprovalVO> indicatorDetailSchemeApprovalVOS = kpiMapper.selectDetailSchemeByProcessInstanceId(processInstanceId);
        System.out.println("审批界面的不带附件方案数据为：" + indicatorDetailSchemeApprovalVOS);
        for (IndicatorDetailSchemeApprovalVO indicatorDetailSchemeApprovalVO : indicatorDetailSchemeApprovalVOS) {
            List<KPISchemeAttachment> kpiSchemeAttachments = kpiAttachmentMapper.selectAttachmentBySchemeId(indicatorDetailSchemeApprovalVO.getId());
            indicatorDetailSchemeApprovalVO.setKpiSchemeAttachments(kpiSchemeAttachments);
        }
        System.out.println("审批界面的完整方案数据为：" + indicatorDetailSchemeApprovalVOS);
        return JsonResult.ok(indicatorDetailSchemeApprovalVOS);
    }

    @ApiOperation(value = "方案审批人审批节点")
    @Transactional
    @PostMapping("/update_schemeStatus/")
    public JsonResult updateSchemeStatusById(@RequestBody List<IndicatorDetailSchemeDTO> indicatorDetailSchemeDTOS) {
        for (IndicatorDetailSchemeDTO indicatorDetailSchemeDTO : indicatorDetailSchemeDTOS) {
            kpiMapper.updateSchemeStatus(indicatorDetailSchemeDTO);
        }
        Map<String, Object> variables = new HashMap<>();
        String approvalResult = indicatorDetailSchemeDTOS.get(0).getApprovalResult();
        System.out.println("审核跳转值：" + approvalResult);
        variables.put("approvalResult", approvalResult);
        String approvalTaskId = indicatorDetailSchemeDTOS.get(0).getApprovalTaskId();
        taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(approvalTaskId).withVariables(variables).build());
        return JsonResult.ok();
    }

    @ApiOperation(value = "获取方案的工作计划")
    @GetMapping("/scheme_task/{kpiDetailId}/{type}")
    public JsonResult selectKpiTasksByKpiDetailId(@PathVariable Integer kpiDetailId, @PathVariable String type) {
        List<GanttTaskVO> schemeTasks = taskMapper.selectTaskByKpiDetailId(kpiDetailId);
        System.out.println("获取的任务数据为" + schemeTasks);
        int size = schemeTasks.size();
        long count = schemeTasks.stream().filter(task -> "已完成".equals(task.getStatusName())).count();
        String percentStr = "0%";
        if (size > 0) {
            double percent = (double) count / size * 100;
            percentStr = String.format("%.0f%%", percent); // 保留整数百分比
        }
        String complete = count + "/" + size + " (" + percentStr + ")";
        switch (type) {
            case "kpi":
                kpiMapper.updateIndicatorDetailCompleteById(kpiDetailId, complete);
                break;
            case "plan":
                kpiMapper.updateIndicatorDetailPlanCompleteById(kpiDetailId, complete);
                break;
            case "custom":
                kpiMapper.updateCustomIndicatorDetailPlanCompleteById(kpiDetailId, complete);
                break;
        }
        for (GanttTaskVO ganttTaskVO : schemeTasks) {
            TaskCompleteApplyVO taskCompleteApplyVO = taskMapper.selectTaskCompleteLatestApplyByTaskId(ganttTaskVO.getId());
            if (taskCompleteApplyVO != null && taskCompleteApplyVO.getApprover() == null) {
                ganttTaskVO.setLatestTaskCompleteApplyVO(taskCompleteApplyVO);
                List<TaskAttachment> taskAttachments = taskAttachmentMapper.selectAttachmentByTaskId(ganttTaskVO.getId());
                taskCompleteApplyVO.setTaskAttachments(taskAttachments);
            }
            List<TaskDelayVO> taskDelayVOS = taskDelayMapper.selectTaskDelayById(ganttTaskVO.getProcessInstanceId());
            if (taskDelayVOS != null) {
                for (TaskDelayVO taskDelayVO : taskDelayVOS) {
                    if (taskDelayVO.getDelayApprovedDate() == null) {
                        if (ganttTaskVO.getLatestTaskDelayApplyVO() == null) {
                            ganttTaskVO.setLatestTaskDelayApplyVO(taskDelayVO);
                        } else if (taskDelayVO.getDelayProposedDate().after(ganttTaskVO.getLatestTaskDelayApplyVO().getDelayProposedDate())) {
                            ganttTaskVO.setLatestTaskDelayApplyVO(taskDelayVO);
                        }
                    }
                }
            }
            enrichGanttTaskVO(ganttTaskVO);
        }
        System.out.println("经过丰富后的任务数据为" + schemeTasks);
        return JsonResult.ok(schemeTasks);
    }

    // 辅助方法，用于丰富GanttTaskVO对象的数据，为各种性质的任务增加了发布时附件、汇报时数据、评论时附件、历史延期数据、任务纪要、计划纪要、完成纪要、协调纪要以及评论纪要数据
    // 其他任务字段都在上面方法中对应的taskMapper中获得。
    private void enrichGanttTaskVO(GanttTaskVO ganttTaskVO) {
        try {
            Integer id = ganttTaskVO.getId();
            String processInstanceId = ganttTaskVO.getProcessInstanceId();
            List<TaskAttachment> taskAttachments = taskAttachmentMapper.selectAttachmentByTaskId(id);
            List<TaskAttachment> releaseAttachments = new ArrayList<>();
            List<TaskAttachment> reportAttachments = new ArrayList<>();
            List<TaskAttachment> commentAttachments = new ArrayList<>();
            List<TaskAttachment> completeAttachments = new ArrayList<>();
            for (TaskAttachment taskAttachment : taskAttachments) {
                switch (taskAttachment.getSource()) {
                    case "发布时":
                        releaseAttachments.add(taskAttachment);
                        break;
                    case "汇报时":
                        reportAttachments.add(taskAttachment);
                        break;
                    case "评论时":
                        commentAttachments.add(taskAttachment);
                        break;
                    case "完成申请时":
                        completeAttachments.add(taskAttachment);
                }
            }
            ganttTaskVO.setReleaseAttachments(releaseAttachments);
            ganttTaskVO.setReportAttachments(reportAttachments);
            ganttTaskVO.setCommentAttachments(commentAttachments);
            ganttTaskVO.setCompleteAttachments(completeAttachments);
            List<TaskHistoryDelayVO> taskHistoryDelayVOS = taskDelayMapper.selectTaskHistoryDelayById(processInstanceId);
            // 处理延期状态
            Date now = new Date();
            Date taskEndDate = taskMapper.selectTaskEndDateById(id);
            boolean isDelayed = taskHistoryDelayVOS == null || taskHistoryDelayVOS.isEmpty();
            if (now.after(taskEndDate) && isDelayed && ganttTaskVO.getActualFinishingTime() == null) {
                ganttTaskVO.setStatusName("已延期");
            }
            if (taskHistoryDelayVOS != null) {
                List<TaskHistoryDelayVO> approvedDelays = new ArrayList<>();
                Date latestApprovalDate = null;
                for (TaskHistoryDelayVO taskHistoryDelayVO : taskHistoryDelayVOS) {
                    if (taskHistoryDelayVO.getDelayApprovedDate() != null) {
                        approvedDelays.add(taskHistoryDelayVO);
                        if (latestApprovalDate == null || taskHistoryDelayVO.getDelayApprovedDate().after(latestApprovalDate)) {
                            latestApprovalDate = taskHistoryDelayVO.getDelayApprovedDate();
                        }
                    }
                }
                ganttTaskVO.setTaskHistoryDelayVOS(approvedDelays);
                ganttTaskVO.setDelayApprovedDate(latestApprovalDate);
            } else {
                ganttTaskVO.setDelayApprovedDate(taskMapper.selectTaskEndDateById(ganttTaskVO.getId()));
            }
            ganttTaskVO.setContentSummaries(taskSummaryMapper.selectContentSummariesByTaskId(id));
            ganttTaskVO.setTaskMilestones(taskMilestoneMapper.selectTaskMilestoneByTaskId(id));
            ganttTaskVO.setTaskCommentSummaries(taskCommentMapper.selectTaskCommentsByTaskId(id));
            ganttTaskVO.setTaskCompleteSummaries(taskCompleteSummaryMapper.selectCompleteSummariesByTaskId(id));
            ganttTaskVO.setTaskPlanSummaries(taskPlanSummaryMapper.selectPlanSummariesByTaskId(id));
            ganttTaskVO.setTaskCoordinateSummaries(taskCoordinateSummaryMapper.selectCoordinateSummariesByTaskId(id));
        } catch (Exception e) {
            System.out.println("Error processing GanttTaskVO: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
